import { HttpClient } from '@angular/common/http';
import { Component, OnInit, ViewChild } from '@angular/core';
import { IonContent, NavController } from '@ionic/angular';

// 导入高德地图服务
import { load } from '@amap/amap-jsapi-loader';
// import AMapLoader from '@amap/amap-jsapi-loader';
@Component({
  selector: 'app-tab2',
  templateUrl: 'tab2.page.html',
  styleUrls: ['tab2.page.scss'],
})
export class Tab2Page {
  // 定位服务
  geoloc = window.navigator.geolocation;
  city: any; // 当前定位城市
  lat: any; // 纬度
  long: any; // 经度
  lists: any; // 电影列表
  cid = 1;
  page = 1;
  @ViewChild('content') content: IonContent;
  constructor(public http: HttpClient, public nav: NavController) {}

  ngOnInit() {
    const url = '/movie/index.php?cid=1';
    this.http.get(url).subscribe((res: any) => {
      console.log(res);
      this.lists = res;
    });
    // 获取定位
    this.getLocation();
  }
  loadLists(e) {
    const cid = e.detail.value;
    if (this.cid == cid) return;
    const url = '/movie/index.php?cid=' + cid;
    this.http.get(url).subscribe((res: any) => {
      console.log(res);
      this.lists = res;
    });
    this.page = 1;
    this.cid = cid;
    this.content.scrollToTop(0);
  }
  // 触底加载数据
  loadData(e) {
    const url = `/movie/index.php?cid=${this.cid}&offset=${this.page * 20}`;
    console.log(this.page * 20);
    this.http.get(url).subscribe((res: any) => {
      console.log(res);
      if (res.length < 20) e.target.disabled = true;
      res = [...this.lists, ...res];
      this.lists = res;
    });
    this.page++;
    e.target.complete();
  }
  // 下拉刷新 加载第一页数据
  doRefresh(e) {
    const url = `/movie/index.php?cid=${this.cid}`;
    this.http.get(url).subscribe((res: any) => {
      console.log(res);
      this.lists = res;
    });
    e.target.complete();
  }
  // 获取定位
  getLocation() {
    this.geoloc.getCurrentPosition(
      (msg) => {
        console.log(msg);
        this.lat = msg.coords.latitude;
        this.long = msg.coords.longitude;
        // 逆地理编码
        // //restapi.amap.com/v3/geocode/regeo?key=6b5c25e5e62b0a6f011f0c5d64aabb98&location=${this.long},${this.lat}
        // 周边搜索
        // //restapi.amap.com/v3/place/around?key=6b5c25e5e62b0a6f011f0c5d64aabb98&location=${this.long},${this.lat}&keywords=影院&offset=20&page=1&extensions=all
        const url = `//restapi.amap.com/v3/geocode/regeo?key=6b5c25e5e62b0a6f011f0c5d64aabb98&location=${this.long},${this.lat}`;
        this.http.get(url).subscribe((res: any) => {
          console.log(res);
          this.city = res.regeocode.addressComponent.city.slice(0, -1);
        });
      },
      (err) => console.log('err:' + err),
      { timeout: 5000 }
    );
  }
  segmentChanged(e) {
    console.log(e.detail.value);
    this.nav.navigateForward('/cinema');
  }
}
